<?php

declare(strict_types=1);

namespace App\Controller;

use App\Library\Common;
use App\Model\ScmFileinfo;
use Hyperf\DbConnection\Db;
use Hyperf\Validation\Rule;

class FileSaveController extends AbstractController
{
    public function add()
    {
        $params = $this->request->inputs(['file_name','file_path','file_type','hash','file_size','with','height']);
        $this->validation(
            $params,
            [
                'file_name' => [
                    "required",
                    "string",
                ],
                'file_path' => [
                    "required",
                    "string",
                ],
                'file_type' => [
                    "required",
                    "string",
                ],
                'hash' => [
                    "required",
                    "string",
                ],
                'file_size' => [
                    "integer",
                ],
                'with' => [
                    "integer",
                ],
                'height' => [
                    "integer",
                ],
            ],
            );
        $uploadDir = $params['file_path'];
        $fileName = $params['file_name'];
        $imagetype = ltrim(strrchr($params['file_name'],'.'),'.');
        $file_data = array(
            'user_id' => $this->getAdminId(),
            'admin_id' => 0,
            'filesize' => isset($params['file_size'])?$params['file_size']:0,
            'imagewidth' => isset($params['with'])?$params['with']:0,
            'imageheight' => isset($params['height'])?$params['height']:0,
            'imagetype' => $imagetype,
//            'imageframes' => 0,
            'mimetype' => $imagetype,
            'url' => $uploadDir . $fileName,
            'uploadtime' => time(),
            'storage' => config('file.default'),
            'sha1' => isset($params['hash'])?$params['hash']:0,
            'extparam' => json_encode([]),
        );
        $info = ScmFileinfo::query()->where('sha1',$params['hash'])->first(['url','url as fullurl','fileinfo_id']);
        if(!$info){
            $file_id = ScmFileinfo::query()->insertGetId(Common::filter_null($file_data));
            $full_url = Common::cdnurl($file_data['url']);
            $info =  [
                'url' => $params['file_path'].$params['file_name'],
                'fileinfo_id' => $file_id,
                'fullurl' => $full_url
            ];
        }

        return $this->jsonResponse->success($info,'下载链接');
    }
}
